const USARTService = require("../services/usartServices");

const usartService = new USARTService("COM89", 115200); // 根据实际情况修改串口名称和波特率

const usartController = {
  initializeSerialPort: async (req, res) => {
    const result = await usartService.initialize();
    if (result.success) {
      res.status(200).send({code:0,msg:result.message});
    } else {
      res.status(500).send({ code: 1, msg: result.message });
    }
  },

  sendDataToSTM32: (req, res) => {
    const { data } = req.body;

    // 检查是否初始化完成
    if (!usartService.isInitialized) {
      return res.status(500).send({code:1,msg:"串口尚未初始化"});
    }

    usartService.sendData(data);
    res.status(200).send({code: 0,msg:"数据已发送到STM32"});
  },

  close: () => {
    try {
      const res = usartService.close();
      if(res)
        res.status(200).send({code: 0,msg: "串口关闭成功"});
    } catch (e) {
      res.status(400).send({ code: 1, msg: "串口关闭失败" });
    }
  }
};

module.exports = usartController;
